package algorithm.linear;

import java.util.Arrays;

/**
 * 顺序循环队列
 * @param <E>
 */
public class SeqQueue<E> implements QQueue<E> {
    //存储队列的数据元素
    private Object[] value;
    //队列的头尾下标
    private int front,rear;

    public SeqQueue(int capacity) {
        this.value = new Object[Math.abs(capacity)];
        this.front = this.rear = 0;
    }

    public SeqQueue() {
        this(10);
    }


    public boolean isEmpty() {
        return this.front == this.rear;
    }

    //入队
    public boolean enqueue(E element) {
        if (element == null)
            return false;
        //若队列满了，则扩容，如果+1满了，取模值为0
        if (this.front==(this.rear+1)%this.value.length){
            Object[] temp = this.value;
            this.value = new Object[this.value.length*2];
            int i = this.front,j=0;
            while(i!=this.rear){
                this.value[j] = temp[i];
                i = (i+1) % temp.length;//下一个位的值
                j++;
            }
            this.front = 0;
            this.rear = j;
        }
        this.value[this.rear] = element;
        this.rear = (this.rear+1) % this.value.length;
        return true;
    }
    //出队
    public E dequeue() {
        if (!isEmpty()) {
            E temp = (E) this.value[this.front];
            this.front = (this.front+1) % this.value.length;
            return temp;
        }
        return null;
    }

    @Override
    public String toString() {
        return "SeqQueue{" +
                "value=" + Arrays.toString(value) +
                ", front=" + front +
                ", rear=" + rear +
                '}';
    }
}
